package APIs.twitter;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

public class FileManipulation {
	/**
	 * Writes a image from a particular URL out to a location on the hard drive
	 * @param URL
	 * @param destination
	 * @throws IOException 
	 */
	public static void writeImageToDisk(String address, String destination, String filename, String username) throws IOException {
//		System.out.println("img variables: " + address + " " + destination + " " + filename);
//		System.out.println("FILENAME: " + parseFilename(address));
		
		URL url = new URL(address); // first we create a URL object
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("User-agent", "Mozilla/5.0");
		InputStream in = conn.getInputStream(); // open the provided URL
		OutputStream out = new BufferedOutputStream(new FileOutputStream(destination + parseFilename(address)));
		
		// Now we will copy over the image byte by byte
		int read  = 1;
		while((read = in.read()) != -1) {
			out.write(read);
		}
		
		updateInventory(username,parseFilename(address)); // update our file inventory
		
		// close our input and output streams
		in.close();
		out.close();
	}
	
	public static void updateInventory(String username, String imageName) throws IOException {
		BufferedWriter outFile = new BufferedWriter(new FileWriter(username + ".txt",true));
		
		// write our image name out to the file
		outFile.append(imageName);
		outFile.newLine(); // write a newline
		
		outFile.flush(); // Flush the file
		outFile.close(); // Close the file
	}
	
	private static Vector<String> ReadInventory(String username) throws IOException {
		Vector<String> retVal = new Vector<String>();
		
		try {
			BufferedReader inFile = new BufferedReader(new FileReader(username + ".txt"));
			// write our image name out to the file
			while(inFile.ready()) {
				retVal.add(inFile.readLine());
			}
			
			// close the file
			inFile.close();
		} catch (Exception e) {
			// if we dont have a file, this will catch the no file error and still return an empty buffer
			//e.printStackTrace();
		}
		
		return retVal;
	}
	
	public static boolean isNewFile(String filename, String username) throws IOException {		
		Vector<String> files = ReadInventory(username); // first we need to read the inventory in
		
		return !files.contains(filename);
	}
	
	public static String parseFilename(String in) {
		String out = in.split(".com/")[1];
		
		return out;
	}
}
